// pages/calendar/calendar.js
const menuData = require('../../data/menu-data1.js').default
const recipeData = require('../../recipe-data.js').default;

const recipeNameMap = {
  // 6龄月
  '米粉（与水比例10:1）': '米粉',
  '米粉（与水比例8:1）': '米粉',
  '米粉（与水比例8:1）+土豆泥': ['米粉', '土豆泥'],
  '米粉（与水比例8:1）+土豆泥+核桃油': ['米粉', '土豆泥'],
  '米粉（与水比例8:1）+胡萝卜泥+核桃油': ['米粉', '胡萝卜泥'],
  '米粉（与水比例7:1）+胡萝卜泥+核桃油': ['米粉', '胡萝卜泥'],
  '米粉（与水比例7:1）+南瓜泥+核桃油': ['米粉', '南瓜泥'],
  '米粉（与水比例6:1）+红薯泥+核桃油': ['米粉', '红薯泥'],
  '米粉（与水比例6:1）+芹菜泥+核桃油': ['米粉', '芹菜泥'],
  '米粉（与水比例5:1）+红薯泥+芝麻酱+核桃油': ['米粉', '红薯泥'],
  '米粉（与水比例5:1）+胡萝卜泥+芝麻酱+核桃油': ['米粉', '胡萝卜泥'],
  '米粉（与水比例5:1）+紫薯泥+核桃油': ['米粉', '紫薯泥'],
  '米粉（与水比例5:1）+山药泥+南瓜泥': ['米粉', '山药泥', '南瓜泥'],
  
  // 7龄月
  '香蕉泥': '香蕉泥',
  '苹果泥': '苹果泥',
  '梨泥': '梨泥',
  '西瓜汁': '西瓜汁',
  
  // 8龄月
  '西兰花南瓜奶粉米糊': ['西兰花泥', '南瓜泥'],
  '紫薯胡萝卜菜花粥': ['紫薯泥', '胡萝卜泥'],
  '菠菜花菜鳕鱼粥': ['菠菜泥', '花菜泥'],
  
  // 9龄月
  '牛肉青菜胡萝卜骨汤面': ['牛肉泥', '胡萝卜泥'],
  '虾仁豆腐豌豆高汤面': ['虾仁泥', '豆腐泥'],
  
  // 10龄月
  '番茄肉酱意大利面': '番茄肉酱意大利面',
  '骨汤蒸蛋羹': '蒸蛋羹',
  
  // 11龄月
  '土豆焗奶酪': '土豆焗奶酪',
  '银耳雪梨羹': '银耳雪梨羹',
  
  // 12龄月
  '青菜猪肉馅小饺子': '猪肉馅饺子',
  '鲜肉虾仁香菇小馄饨': '鲜肉虾仁香菇小馄饨',
  '虾仁香菇葱花蛋饼': '虾仁蛋饼'
};

function findRecipe(recipeName) {
  // 1. 直接查找完整名称
  let recipe = recipeData.find(r => r.name === recipeName);
  if (recipe) return recipe;

  // 2. 查找映射名称
  const mappedNames = recipeNameMap[recipeName];
  if (mappedNames) {
    if (Array.isArray(mappedNames)) {
      // 如果是组合菜品，返回第一个找到的食谱
      for (const name of mappedNames) {
        recipe = recipeData.find(r => r.name === name);
        if (recipe) return recipe;
      }
    } else {
      recipe = recipeData.find(r => r.name === mappedNames);
      if (recipe) return recipe;
    }
  }

  // 3. 模糊匹配
  const simplifiedName = recipeName.split(/[+（）\s]/)[0]; // 提取主要食材名称
  return recipeData.find(r => r.name.includes(simplifiedName));
}

Page({
  data: {
    currentMonth: '6龄月',
    currentDay: 1,
    daysInMonth: 31,
    dailyMenu: {
      breakfast: [],
      lunch: [],
      snack: [],
      dinner: []
    },
    diaryContent: '', // 日记内容
    showEmoji: false, // 是否显示表情选择器
    emojiList: ['😊', '😃', '😅', '😂', '🤣', '😇', '😉', '😍', '🤩', '😘', 
                '😋', '😛', '😜', '🤪', '😝', '🤗', '🤭', '🤫', '🤔', '🤐',
                '😐', '😑', '😶', '😏', '😒', '🙄', '😬', '🤥', '😌', '😔',
                '😪', '🤤', '😴', '😷', '🤒', '🤕', '🤢', '🤮', '🤧', '🥵'],
    showRecipe: false,
    selectedRecipe: null,
    babyBirthday: '', // 宝宝出生日期
    babyAge: '', // 宝宝月龄
    showDatePicker: false,
    years: [],
    months: [],
    days: [],
    datePickerValue: [0, 0, 0],
    tempDate: null
  },

  onLoad() {
    // 初始化当前日期
    this.setData({
      currentMonth: '6龄月',
      currentDay: 1,
      daysInMonth: this.getDaysInMonth('6')
    })
    this.updateDailyMenu()
    this.loadDiary() // 加载日记内容
    this.initDatePicker();
    this.loadBabyBirthday();
  },

  // 切换月份
  switchMonth(e) {
    const month = e.currentTarget.dataset.month
    this.setData({
      currentMonth: month + '龄月',
      currentDay: 1, // 切换月份时重置为第一天
      daysInMonth: this.getDaysInMonth(month)
    })
    this.updateDailyMenu()
    this.loadDiary() // 加载新日期的日记
  },

  // 切换日期
  switchDay(e) {
    const day = e.currentTarget.dataset.day
    this.setData({
      currentDay: day
    })
    this.updateDailyMenu()
    this.loadDiary() // 加载新日期的日记
  },

  // 获取月份的天数
  getDaysInMonth(month) {
    const monthData = menuData[month + '龄月'] || []
    return monthData.length
  },

  // 更新每日菜单
  updateDailyMenu() {
    const monthData = menuData[this.data.currentMonth] || []
    const dayData = monthData.find(item => Object.keys(item)[0] === String(this.data.currentDay))
    
    if (dayData) {
      const menuForDay = dayData[this.data.currentDay]
      // 转换数据格式以匹配界面显示
      const formattedMenu = {
        breakfast: [{
          name: '早午餐',
          desc: menuForDay['早午餐（10点）'] || '暂无安排'
        }],
        lunch: [{
          name: '午餐',
          desc: menuForDay['午餐（12-1点）'] || '暂无安排'
        }],
        snack: [{
          name: '点心',
          desc: menuForDay['点心（3-4点）'] || '暂无安排'
        }],
        dinner: [{
          name: '晚餐',
          desc: menuForDay['晚餐(6-7点)'] || '暂无安排'
        }]
      }
      
      this.setData({
        dailyMenu: formattedMenu
      })
    } else {
      // 如果没有找到对应日期的数据，显示暂无安排
      const emptyMenu = {
        breakfast: [{
          name: '早午餐',
          desc: '暂无安排'
        }],
        lunch: [{
          name: '午餐',
          desc: '暂无安排'
        }],
        snack: [{
          name: '点心',
          desc: '暂无安排'
        }],
        dinner: [{
          name: '晚餐',
          desc: '暂无安排'
        }]
      }
      this.setData({
        dailyMenu: emptyMenu
      })
    }
  },

  // 日记相关方法
  onDiaryInput(e) {
    this.setData({
      diaryContent: e.detail.value
    })
  },

  // 保存日记
  saveDiary() {
    const key = `diary_${this.data.currentMonth}_${this.data.currentDay}`
    wx.setStorage({
      key,
      data: this.data.diaryContent,
      success: () => {
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        })
      },
      fail: () => {
        wx.showToast({
          title: '保存失败',
          icon: 'error'
        })
      }
    })
  },

  // 加载日记
  loadDiary() {
    const key = `diary_${this.data.currentMonth}_${this.data.currentDay}`
    wx.getStorage({
      key,
      success: (res) => {
        this.setData({
          diaryContent: res.data
        })
      },
      fail: () => {
        this.setData({
          diaryContent: ''
        })
      }
    })
  },

  // 显示/隐藏表情选择器
  toggleEmoji() {
    this.setData({
      showEmoji: !this.data.showEmoji
    })
  },

  // 选择表情
  selectEmoji(e) {
    const emoji = e.currentTarget.dataset.emoji
    const content = this.data.diaryContent + emoji
    this.setData({
      diaryContent: content,
      showEmoji: false
    })
  },

  showRecipeDetail(e) {
    const recipeName = e.currentTarget.dataset.recipeName;
    if (recipeName === '暂无安排') return;
    
    const recipe = findRecipe(recipeName);
    
    if (recipe) {
      this.setData({
        showRecipe: true,
        selectedRecipe: recipe
      });
    } else {
      wx.showToast({
        title: '暂无此食谱详情',
        icon: 'none'
      });
    }
  },

  closeRecipe() {
    this.setData({
      showRecipe: false,
      selectedRecipe: null
    });
  },

  // 初始化日期选择器数据
  initDatePicker() {
    const date = new Date();
    const years = [];
    const months = [];
    const days = [];

    for (let i = date.getFullYear() - 3; i <= date.getFullYear(); i++) {
      years.push(i);
    }
    for (let i = 1; i <= 12; i++) {
      months.push(i);
    }
    for (let i = 1; i <= 31; i++) {
      days.push(i);
    }

    this.setData({
      years,
      months,
      days
    });
  },

  // 显示日期选择器
  showDatePicker() {
    this.setData({
      showDatePicker: true
    });
  },

  // 取消选择
  cancelDatePicker() {
    this.setData({
      showDatePicker: false,
      tempDate: null
    });
  },

  // 确认选择
  confirmDatePicker() {
    if (this.data.tempDate) {
      const dateStr = this.formatDate(this.data.tempDate);
      this.setData({
        babyBirthday: dateStr,
        showDatePicker: false
      });
      this.calculateBabyAge();
      this.saveBabyBirthday(dateStr);
    }
  },

  // 日期选择器变化事件
  onDatePickerChange(e) {
    const val = e.detail.value;
    const year = this.data.years[val[0]];
    const month = this.data.months[val[1]];
    const day = this.data.days[val[2]];
    
    this.setData({
      tempDate: new Date(year, month - 1, day)
    });
  },

  // 计算宝宝月龄
  calculateBabyAge() {
    if (!this.data.babyBirthday) return;
    
    const birth = new Date(this.data.babyBirthday);
    const now = new Date();
    
    let months = (now.getFullYear() - birth.getFullYear()) * 12;
    months += now.getMonth() - birth.getMonth();
    
    if (now.getDate() < birth.getDate()) {
      months--;
    }
    
    this.setData({
      babyAge: `${months}个月`,
      currentMonth: `${months}龄月`
    });
    
    // 更新食谱显示
    this.updateDailyMenu();
  },

  // 保存出生日期到本地存储
  saveBabyBirthday(date) {
    wx.setStorage({
      key: 'babyBirthday',
      data: date
    });
  },

  // 加载保存的出生日期
  loadBabyBirthday() {
    wx.getStorage({
      key: 'babyBirthday',
      success: (res) => {
        this.setData({
          babyBirthday: res.data
        });
        this.calculateBabyAge();
      }
    });
  },

  // 格式化日期
  formatDate(date) {
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${year}-${month}-${day}`;
  }
}) 